﻿using System;
using System.IO.Ports;


namespace ComTest
{
    public delegate void SerialPortHandlerDelegate(string receivedMessage);
    public class SerialPortHandler
    {
        #region Properties
        
        //singleton instance
        public static SerialPortHandler Instance { get { return ThisSerialPortHandler; } }
        private static readonly SerialPortHandler ThisSerialPortHandler = new SerialPortHandler();

        public event SerialPortHandlerDelegate DataReceived;
        private SerialPort _port;
        private string _receivedMsg = "";
        private bool _portAvailible;

        #endregion

        private SerialPortHandler()
        {
            try
            {
                _port = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
                _port.DataReceived += _dataReceived;
                _port.Open(); 
                _portAvailible = true;
            }
            catch (Exception e)
            {
                _portAvailible = false;
            }
        }

        public void Write(string s)
        {
            if(_portAvailible)
                _port.WriteLine(s);
        }

        private void _dataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            _receivedMsg += _port.ReadExisting();
            if (_receivedMsg.Contains("\n"))   //this means we have received a full sentence
            {
                if (DataReceived != null) 
                    DataReceived(_receivedMsg);
                _receivedMsg = "";
            }
        }
    }
}
